"use server"

import {ActionState, LoginForm} from "@/lib/zod/types";
import {LoginSchema} from "@/lib/zod/schema";
import db from "@/lib/db";
import {generateToken} from "@/lib/utils";
import {hmacEncode} from "@/lib/password";
import {setSession} from "@/lib/session";


export const login = async (_state: ActionState<LoginForm>, fromData: FormData) => {
    const entries = Object.fromEntries(fromData.entries());
    const safeParse = LoginSchema.safeParse(entries);

    if (!safeParse.success) {
        const errors = safeParse.error.flatten().fieldErrors;

        return {
            code: 402,
            msg: "参数校验失败",
            errors,
            input:{
                email:entries.email as string,
                password:entries.password as string,
            }
        }
    }

    const data = safeParse.data;
    const user = await db.users.findUnique({
        where: {
            email: data.email,
            status:"active"
        }
    });

    const pwd = hmacEncode(data.password, process.env.USER_LOGIN_PASSWORD_SECRET!);
    if (!user || user.password != pwd) {

        return {
            code: 403,
            msg: "密码或账号输入错误",
            input: {
                email: entries.email as string,
                password: entries.password as string,
            }
        };
    }

    const token = await generateToken({userId: user.userId, sex: user.sex, email: user.email, username: user.username, image: user.image});
    await setSession(token);

    return {
        code: 200,
        msg: "登录成功",
    };
}